<template>
  <div class="l-from-body" style="padding: 8px 48px 8px 48px">
    <el-form
      :disabled="loading"
      :model="formData"
      :rules="rules"
      label-position="left"
      size="mini"
      ref="form"
      label-width="100px"
    >
      <el-divider content-position="left">密码修改</el-divider>
      <el-form-item label="旧密码" prop="oldPassword">
        <el-input v-model="formData.oldPassword" show-password></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="password">
        <el-input v-model="formData.password" show-password></el-input>
      </el-form-item>
      <el-form-item label="重复新密码" prop="password2">
        <el-input v-model="formData.password2" show-password></el-input>
      </el-form-item>
      <el-form-item>
        <el-button :loading="loading" type="primary" @click="onSubmit">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
const api = window.$api.organization.user;
export default {
  name: "user-password",
  data() {
    return {
      loading: false,
      formData: {
        oldPassword: "",
        password: "",
        password2: "",
      },
      rules: {
        oldPassword: [
          { required: true, message: "请输入旧密码" },
          { validator: this.validatorPassword, trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入新密码" }],
        password2: [
          { required: true, message: "请再输入新密码" },
          {
            validator: (rule, value, callback) => {
              if (this.formData.password2 != this.formData.password) {
                callback(new Error("两次密码输入不一致"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
      },
    };
  },
  computed: {},
  created() {},
  methods: {
    validatorPassword(rule, value, callback) {
      //console.log('test')
      api.validatorPassword(this.$md5(value)).then((res) => {
        if (res.data.code == 200 && res.data.data) {
          callback();
        } else {
          callback(new Error(res.data.info));
        }
      });
    },
    onSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.loading = true;
          const req = {
            password: this.$md5(this.formData.password),
            oldPassword: this.$md5(this.formData.oldPassword),
          };
          api
            .updatePassword(req)
            .then(() => {
              this.$message({
                type: "success",
                message: "修改成功!",
              });

              setTimeout(() => {
                this.$store.dispatch("organization/user/fedLogOut").then(() => {
                  this.$router.push({ path: "/login" });
                });
              }, 500);
            })
            .catch(() => {
              this.loading = false;
            });
        }
      });
    },
  },
};
</script>
